package com.cscec5b.inspection.controller;

//import com.cscec5b.inspection.common.ApiResp;
import com.cscec5b.inspection.config.PasswordUtil;
import com.cscec5b.inspection.dto.LoginRequest;
import com.cscec5b.inspection.entity.User;
import com.cscec5b.inspection.repository.UserRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

//import static org.aspectj.bridge.MessageUtil.fail;

@RestController
@RequestMapping("/api/user")
public class UserController {

//    @Autowired
//    private UserRepository userRepository;
private final UserRepository userRepository;
//    private final PasswordEncoder passwordEncoder; // 若未引入也可改为 Optional 注入

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
//        this.passwordEncoder = passwordEncoder.orElse(null);
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginRequest p, HttpServletRequest req) {
        User user = userRepository.findByUsername(p.getUsername())
                .orElseThrow(() -> new RuntimeException("用户名不存在"));

//        boolean passOk = (passwordEncoder != null)
//                ? passwordEncoder.matches(p.getPassword(), user.getUserPassword())
//                : Objects.equals(p.getPassword(), user.getUserPassword()); // 开发期可用明文
//
//        if (!passOk) throw new RuntimeException("密码错误");

        // 2) 明文 → 双MD5（小写）后与库里 user_password 比较
        String inputDoubleMd5 = PasswordUtil.doubleMd5(p.getPassword()).toLowerCase();
        String stored = user.getPassword() == null ? "" : user.getPassword().toLowerCase();

        if (!PasswordUtil.constantTimeEquals(inputDoubleMd5, stored)) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户名或密码错误");
        }

        HttpSession session = req.getSession(true);
        String norm = normalizeCode(user.getUserCode()); // 统一成数据库格式，例如 "001"
        session.setAttribute("USER_CODE", norm);

        return Map.of(
                "sessionId", session.getId(),                  // 前端放到 X-Auth-Token
                "user", Map.of("username", user.getUsername(), "userCode", norm)
        );
    }

    @PostMapping("/logout")
    public Map<String, Object> logout(HttpServletRequest req) {
        HttpSession s = req.getSession(false);
        if (s != null) s.invalidate();
        return Map.of("ok", true);
    }

    private String normalizeCode(String raw) {
        if (raw == null) return null;
        String digits = raw.replaceAll("\\D+", "");
        return digits.isEmpty() ? null : String.format("%03d", Integer.parseInt(digits));
    }

    public static class LoginRequest {
        private String username, password;
        public String getUsername() { return username; }
        public void setUsername(String v) { this.username = v; }
        public String getPassword() { return password; }
        public void setPassword(String v) { this.password = v; }
    }

//    @PostMapping("/login")
//    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest, HttpSession session) {
//        var opt = userRepository.findByUsername(loginRequest.username());
//        if (opt.isEmpty() || !Objects.equals(opt.get().getPassword(), loginRequest.password())) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
//                    .body(Map.of("message", "用户名或密码错误"));
//        }
//
//        var user = opt.get();
//        session.setAttribute("userId", user.getUserCode());
//        session.setAttribute("username", user.getUsername());
//        session.setAttribute("userRole", user.getRole());
//
//        // ✅ 不要用 Map.of —— 改用 HashMap，允许 null
//        Map<String, Object> body = new HashMap<>();
//        body.put("message", "登录成功");
//        body.put("username", user.getUsername());
//        body.put("role", user.getRole()); // 就算是 null 也没关系
//
//        return ResponseEntity
//                .ok()
//                .contentType(MediaType.APPLICATION_JSON_UTF8) // Spring 5.2 之前
//                .body(Map.of(
//                        "message", "登录成功",
//                        "username", user.getUsername(),
//                        "role", user.getRole()
//                ));
//    }
}